package net.kazed.nextaction.context.activity;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdContext;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ContextEditorActivity extends Activity {

    private static final String cTag = "ContextEditorActivity";
   
    private static final int MENU_REVERT = Menu.FIRST;
    private static final int MENU_DELETE = Menu.FIRST + 1;
    
    private Cursor cursor;
    private boolean isNew;
    private Uri itemUri;
    private GtdContext originalContext;
    private EditText nameWidget;
    private Button saveButton;
    private Button cancelButton;
    private boolean cancelled = false;
        
    @Override
    protected void onCreate(Bundle savedValues) {
        super.onCreate(savedValues);
        
        // Do some setup based on the action being performed.
        final Intent intent = getIntent();
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_EDIT)) {
            isNew = false;
        } else if (action.equals(Intent.ACTION_INSERT)) {
           isNew = true;
        }
        itemUri = intent.getData();
        Intent returnIntent = new Intent();
        returnIntent.setData(itemUri);
        setResult(RESULT_OK, returnIntent);

        cursor = managedQuery(itemUri, GtdContext.FULL_PROJECTION.getFieldNames(), null, null, null);
        
        setContentView(R.layout.context_editor);
        nameWidget = (EditText) findViewById(R.id.name);
        
        saveButton = (Button) findViewById(R.id.save_button);
        saveButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
              finish();
           }
        });
        
        cancelButton = (Button) findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
              if (isNew) {
                 getContentResolver().delete(itemUri, null, null);
              }
              cancelled = true;
              setResult(RESULT_CANCELED);
              finish();
           }
        });
        
        // If we didn't have any trouble retrieving the data, it is now
        // time to get at the stuff.
        if (cursor != null) {
            // Make sure we are at the one and only row in the cursor.
            cursor.moveToFirst();

            // Modify our overall title depending on the mode we are running in.
            if (isNew) {
               setTitle(R.string.title_new_context);
            } else {
                setTitle(R.string.title_edit_context);
            }
            
            originalContext = new GtdContext(cursor);
            populateFields(originalContext);

        } else {
            setTitle(getText(R.string.error_title));
            nameWidget.setText(getText(R.string.error_message));
        }
        
        if (savedValues != null) {
            nameWidget.setText(savedValues.getString(GtdContext.NAME));
        }
        
        // select the description
        nameWidget.selectAll();

    }
    
   @Override
    protected void onResume() {
        super.onResume();
    }

   private void populateFields(GtdContext context) {
       nameWidget.setTextKeepState(context.getName());
   }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
    	Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);		
	}
    
    @Override
    protected void onPause() {
        Log.d(cTag, "onPause+");
        super.onPause();

        if (!cancelled && cursor != null) {
            GtdContext context = new GtdContext(cursor);
            String name = nameWidget.getText().toString();
            context.setName(name);
            
            ContentValues values = new ContentValues();
            context.toValues(values);
            getContentResolver().update(itemUri, values, null, null);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_REVERT, 0, resources.getString(R.string.menu_revert))
          .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r');
       menu.add(0, MENU_DELETE, 1, resources.getString(R.string.menu_delete))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_REVERT:
          populateFields(originalContext);
          break;
       case MENU_DELETE:
          getContentResolver().delete(itemUri, null, null);
          finish();
          break;
       }
       return super.onOptionsItemSelected(item);
    }
    
    /**
     * Take care of deleting a context.  Simply deletes the entry.
     */
    protected void deleteItem() {
        nameWidget.setText("");
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
//            AlertDialog.Builder builder = new AlertDialog.Builder(ContextEditorActivity.this);
//            builder.setTitle(R.string.backup_merge_alert_title).setMessage(R.string.backup_merge_alert_message)
//               .setIcon(android.R.drawable.ic_dialog_alert);
//            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
//                  public void onClick(DialogInterface dialog, int whichButton) {
//                      finish();
//                  }
//            });
//            builder.setNegativeButton(R.string.alert_no, new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int whichButton) {
//                    cancelled = true;
//                    finish();
//                }
//          });
//            builder.show();
//            return true;
//        } else {
//            return super.onKeyDown(keyCode, event);
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(GtdContext.NAME, nameWidget.getText().toString());
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    
}
